package top.anka1.fxgui;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import top.anka1.ims.ZooGUI;
import top.anka1.ims.ZooManagementSystem.*;

import java.util.ArrayList;
import java.util.Optional;
/**
 * MoveAnimalController is a JavaFX controller class that handles the moving of animals between zoos.
 * It provides methods to create vehicle and fuel items, gather caretaker information, and confirm the move.
 * @author Anka
 */
public class MoveAnimalController {
    private ZooGUI zooGUI;
    private Zoo fromZoo;
    private Zoo toZoo;
    private Stage stage;
    @FXML
    private Label MoveAnimalsTitle;
    @FXML
    private TableView<Animal> AnimalsTableView;
    @FXML
    private TableColumn<Animal, String> AnimalNameColumn, SpeciesColumn;
    @FXML
    private TableColumn<Animal, Integer> AgeColumn;

    public Item createVehicle(Stage stage) {
        Item vehicle = new Item("Transport Truck", "VEH_001");
        TextInputDialog dialog = new TextInputDialog();
        dialog.initOwner(stage);
        dialog.setTitle("Vehicle Cost");
        dialog.setHeaderText(null);
        dialog.setContentText("Enter vehicle cost: RMB");

        Optional<String> result = dialog.showAndWait();
        result.ifPresent(input -> {
            try {
                vehicle.setPrice(Double.parseDouble(input));
            } catch (NumberFormatException e) {
                showError(stage, "Invalid vehicle cost");
            }
        });

        return vehicle;
    }

    public Item createFuel(Stage stage) {
        Item fuel = new Item("Diesel Fuel", "FUEL_001");
        TextInputDialog dialog = new TextInputDialog();
        dialog.initOwner(stage);
        dialog.setTitle("Fuel Cost");
        dialog.setHeaderText(null);
        dialog.setContentText("Enter fuel cost: RMB");

        Optional<String> result = dialog.showAndWait();
        result.ifPresent(input -> {
            try {
                fuel.setPrice(Double.parseDouble(input));
            } catch (NumberFormatException e) {
                showError(stage, "Invalid fuel cost");
            }
        });

        return fuel;
    }

    public String[] createCaretakersGUI(Stage stage) {
        int numCaretakers = -1;

        while (numCaretakers < 1 || numCaretakers > 3) {
            TextInputDialog dialog = new TextInputDialog();
            dialog.initOwner(stage);
            dialog.setTitle("Number of Caretakers");
            dialog.setHeaderText(null);
            dialog.setContentText("Enter the number of caretakers (between 1 and 3):");

            Optional<String> result = dialog.showAndWait();
            if (!result.isPresent()) return null;

            try {
                numCaretakers = Integer.parseInt(result.get());
                if (numCaretakers < 1 || numCaretakers > 3) {
                    showError(stage, "Please enter a number between 1 and 3.");
                }
            } catch (NumberFormatException e) {
                showError(stage, "Invalid input! Please enter a number between 1 and 3.");
            }
        }

        String[] caretakers = new String[numCaretakers];
        for (int i = 0; i < numCaretakers; i++) {
            TextInputDialog nameDialog = new TextInputDialog();
            nameDialog.initOwner(stage);
            nameDialog.setTitle("Caretaker Name");
            nameDialog.setHeaderText(null);
            nameDialog.setContentText("Enter name of caretaker " + (i + 1) + ":");

            Optional<String> nameResult = nameDialog.showAndWait();
            if (!nameResult.isPresent()) return null;

            caretakers[i] = nameResult.get();
        }

        return caretakers;
    }

    private void showError(Stage stage, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.initOwner(stage);
        alert.setTitle("Error");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    public void setData(Zoo fromZoo, Zoo toZoo, ArrayList<Animal> animalList, Stage stage, ZooGUI zooGUI) {
        MoveAnimalsTitle.setText("Move from " + fromZoo.getName() + " to " + toZoo.getName());
        this.zooGUI = zooGUI;
        this.fromZoo = fromZoo;
        this.toZoo = toZoo;
        this.stage = stage;
        AnimalNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        AnimalNameColumn.setStyle("-fx-alignment: CENTER;");
        SpeciesColumn.setCellValueFactory(new PropertyValueFactory<>("species"));
        SpeciesColumn.setStyle("-fx-alignment: CENTER;");
        AgeColumn.setCellValueFactory(new PropertyValueFactory<>("age"));
        AgeColumn.setStyle("-fx-alignment: CENTER;");

        ObservableList<Animal> animals = FXCollections.observableArrayList(animalList);
        AnimalsTableView.setItems(animals);
    }

    @FXML
    public void confirmMove() {

        String animalName = AnimalsTableView.getSelectionModel().getSelectedItem().getName();
        if (this.fromZoo.findAnimal(animalName) != -1) {
            Item vehicle = createVehicle(this.stage); // JavaFX中的窗口Stage
            Item fuel = createFuel(this.stage);
            String[] caretakers = createCaretakersGUI(this.stage);
            Logistics logistics = new Logistics(this.fromZoo, this.toZoo, vehicle, fuel, caretakers);
            this.fromZoo.moveAnimal(animalName, this.toZoo, logistics);
            zooGUI.getLogisticsList().add(logistics);

            Alert successAlert = new Alert(Alert.AlertType.INFORMATION);
            successAlert.initOwner(this.stage);
            successAlert.setTitle("Success");
            successAlert.setHeaderText(null);
            successAlert.setContentText("Animal moved successfully!");
            successAlert.showAndWait();
        } else {
            Alert errorAlert = new Alert(Alert.AlertType.ERROR);
            errorAlert.initOwner(this.stage);
            errorAlert.setTitle("Error");
            errorAlert.setHeaderText(null);
            errorAlert.setContentText("Animal not found in " + this.fromZoo.getName());
            errorAlert.showAndWait();
        }
        this.stage.close();
    }
}
